<template>
  <el-dialog
    :visible="showAssign"
    title="分配角色"
    width="30%"
    @close="onCancel"
  >
    <el-row>当前的用户 : {{ user.username }}</el-row>
    <el-row style="margin-top: 10px">当前的角色 : {{ user.role_name }}</el-row>
    <el-form>
      <el-form-item label="分配新角色">
        <el-select v-model="selectId" size="small">
          <el-option
            :label="item.roleName"
            :value="item.id"
            v-for="item in roles"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="end">
        <el-button size="small" @click="onCancel">取消</el-button>
        <el-button size="small" type="primary" @click="onConfirm"
          >确定</el-button
        >
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { roles } from '@/api/roles'
import { assignRoles } from '@/api/users'
export default {
  props: {
    showAssign: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      user: {},
      roles: [],
      selectId: ''
    }
  },
  async created () {
    await this.getRoles()
  },
  methods: {
    async getRoles () {
      this.roles = await roles()
    },
    onCancel () {
      this.user = {}
      this.selectId = ''
      this.$emit('update:showAssign', false)
    },
    async onConfirm () {
      if (this.selectId === '') {
        return this.$message.warning('请选择要分配的角色')
      }
      try {
        await assignRoles({ id: this.user.id, rid: this.selectId })
        this.$message.success('分配成功')
        this.$emit('update:showAssign', false)
        this.$parent.getUsers()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style>
</style>
